package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Leave;
import com.example.demo.mapper.LeaveMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("/leave")
public class LeaveController {

    @Resource
    LeaveMapper leaveMapper;


    @PostMapping
    public Result<?> save(@RequestBody Leave leave,
                          @RequestParam String val1,
                          @RequestParam String val2) {
        //从全局变量拿到时间


        leave.setLeaveDate1(val1);
        leave.setLeaveDate2(val2);
        leaveMapper.insert(leave);
        return Result.success();

    }

    @PutMapping
    public Result<?> update(@RequestBody Leave leave) {
        leaveMapper.updateById(leave);
        return Result.success();

    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        leaveMapper.deleteById(id);
        return Result.success();

    }

    @GetMapping("/Query")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {

        System.out.println("sss");

        LambdaQueryWrapper<Leave> wrapper = Wrappers.<Leave>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Leave::getStuName, search);
        }
        Page<Leave> stuPage = leaveMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(stuPage);

    }

    @PostMapping("/leaveSave")
    public Result<?> wxSave(@RequestBody JSONObject req) {
//        拿到小程序请求传来的请假表单里的数据
        String name = req.getStr("name");
        String reason = req.getStr("reason");
        String course = req.getStr("course");
        String startTime = req.getStr("starTime");
        String endTime1 = req.getStr("endTime");

        //格式化事件
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String starTime = sf.format(new Date(Long.parseLong(startTime)));
        String endTime = sf.format(new Date(Long.parseLong(endTime1)));


        Leave leave = new Leave();
        leave.setStuName(name);
        leave.setCourseName(course);
        leave.setReason(reason);
        leave.setStatus(0);
        leave.setLeaveDate1(starTime);
        leave.setLeaveDate2(endTime);
        System.out.println(leave);
        leaveMapper.insert(leave);
        return Result.success();

    }
}
